# Windows服务安装脚本
# 用于在Windows Server 2019上安装.NET 9应用程序作为Windows服务

param(
    [Parameter(Mandatory=$true)]
    [string]$ServiceName = "LzfyHisService",
    
    [Parameter(Mandatory=$true)]
    [string]$ServiceDisplayName = "Lzfy His Service",
    
    [Parameter(Mandatory=$true)]
    [string]$ServiceDescription = "Lzfy医院信息系统退费服务",
    
    [Parameter(Mandatory=$true)]
    [string]$BinaryPath,
    
    [Parameter(Mandatory=$false)]
    [string]$ServiceAccount = "LocalSystem"
)

# 检查是否以管理员权限运行
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Error "此脚本需要管理员权限运行"
    exit 1
}

# 检查服务是否已存在
$existingService = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
if ($existingService) {
    Write-Host "服务 '$ServiceName' 已存在，正在停止并删除..." -ForegroundColor Yellow
    
    # 停止服务
    if ($existingService.Status -eq 'Running') {
        Stop-Service -Name $ServiceName -Force
        Write-Host "服务已停止" -ForegroundColor Green
    }
    
    # 删除服务
    sc.exe delete $ServiceName
    Start-Sleep -Seconds 2
    Write-Host "服务已删除" -ForegroundColor Green
}

# 验证二进制文件路径
if (-not (Test-Path $BinaryPath)) {
    Write-Error "二进制文件路径不存在: $BinaryPath"
    exit 1
}

# 创建服务
Write-Host "正在创建服务 '$ServiceName'..." -ForegroundColor Blue

$serviceParams = @{
    Name = $ServiceName
    BinaryPathName = $BinaryPath
    DisplayName = $ServiceDisplayName
    Description = $ServiceDescription
    StartupType = "Automatic"
    Credential = if ($ServiceAccount -ne "LocalSystem") { Get-Credential } else { $null }
}

try {
    if ($ServiceAccount -eq "LocalSystem") {
        # 使用sc.exe创建服务，因为New-Service在某些情况下可能有问题
        $scResult = sc.exe create $ServiceName binPath= "\"$BinaryPath\"" DisplayName= "$ServiceDisplayName" start= auto
        if ($LASTEXITCODE -ne 0) {
            throw "sc.exe create failed with exit code $LASTEXITCODE"
        }
        
        # 设置服务描述
        sc.exe description $ServiceName "$ServiceDescription"
        
        Write-Host "服务创建成功" -ForegroundColor Green
    } else {
        New-Service @serviceParams
        Write-Host "服务创建成功" -ForegroundColor Green
    }
    
    # 配置服务恢复选项
    Write-Host "配置服务恢复选项..." -ForegroundColor Blue
    sc.exe failure $ServiceName reset= 86400 actions= restart/5000/restart/10000/restart/30000
    
    # 启动服务
    Write-Host "正在启动服务..." -ForegroundColor Blue
    Start-Service -Name $ServiceName
    
    # 验证服务状态
    $service = Get-Service -Name $ServiceName
    if ($service.Status -eq 'Running') {
        Write-Host "服务 '$ServiceName' 已成功启动" -ForegroundColor Green
        Write-Host "服务状态: $($service.Status)" -ForegroundColor Green
    } else {
        Write-Warning "服务已创建但未能启动，当前状态: $($service.Status)"
        Write-Host "请检查应用程序日志以获取更多信息" -ForegroundColor Yellow
    }
    
} catch {
    Write-Error "创建服务时发生错误: $($_.Exception.Message)"
    exit 1
}

Write-Host "服务安装完成!" -ForegroundColor Green
Write-Host "服务名称: $ServiceName" -ForegroundColor Cyan
Write-Host "显示名称: $ServiceDisplayName" -ForegroundColor Cyan
Write-Host "二进制路径: $BinaryPath" -ForegroundColor Cyan
Write-Host "" 
Write-Host "管理命令:" -ForegroundColor Yellow
Write-Host "  启动服务: Start-Service -Name $ServiceName" -ForegroundColor White
Write-Host "  停止服务: Stop-Service -Name $ServiceName" -ForegroundColor White
Write-Host "  重启服务: Restart-Service -Name $ServiceName" -ForegroundColor White
Write-Host "  查看状态: Get-Service -Name $ServiceName" -ForegroundColor White
Write-Host "  删除服务: sc.exe delete $ServiceName" -ForegroundColor White